import { apiClient } from './apiClient';
import type { 
  PaginatedResponse,
  TenantSettings,
  OrganizationSettings,
  SystemSettings,
  AuditLog
} from '@/types';

export interface GetAuditLogsParams {
  page?: number;
  pageSize?: number;
  search?: string;
  action?: string;
  level?: 'info' | 'success' | 'warning' | 'error';
  userId?: string;
  dateRange?: 'today' | 'week' | 'month';
  startDate?: string;
  endDate?: string;
}

class SettingsService {
  private baseUrl = '/api/settings';

  /**
   * 获取租户设置
   */
  async getTenantSettings(): Promise<TenantSettings> {
    const { data } = await apiClient.get<TenantSettings>(`${this.baseUrl}/tenant`);
    return data;
  }

  /**
   * 更新租户设置
   */
  async updateTenantSettings(settings: Partial<TenantSettings>): Promise<TenantSettings> {
    const { data } = await apiClient.put<TenantSettings>(`${this.baseUrl}/tenant`, settings);
    return data;
  }

  /**
   * 获取组织设置
   */
  async getOrganizationSettings(organizationId: string): Promise<OrganizationSettings> {
    const { data } = await apiClient.get<OrganizationSettings>(`${this.baseUrl}/organization/${organizationId}`);
    return data;
  }

  /**
   * 更新组织设置
   */
  async updateOrganizationSettings(organizationId: string, settings: Partial<OrganizationSettings>): Promise<OrganizationSettings> {
    const { data } = await apiClient.put<OrganizationSettings>(`${this.baseUrl}/organization/${organizationId}`, settings);
    return data;
  }

  /**
   * 获取系统设置
   */
  async getSystemSettings(): Promise<SystemSettings> {
    const { data } = await apiClient.get<SystemSettings>(`${this.baseUrl}/system`);
    return data;
  }

  /**
   * 更新系统设置
   */
  async updateSystemSettings(settings: Partial<SystemSettings>): Promise<SystemSettings> {
    const { data } = await apiClient.put<SystemSettings>(`${this.baseUrl}/system`, settings);
    return data;
  }

  /**
   * 获取审计日志
   */
  async getAuditLogs(params: GetAuditLogsParams): Promise<PaginatedResponse<AuditLog>> {
    const { data } = await apiClient.get<PaginatedResponse<AuditLog>>('/api/audit-logs', {
      params
    });
    return data;
  }

  /**
   * 获取审计日志详情
   */
  async getAuditLogById(id: string): Promise<AuditLog> {
    const { data } = await apiClient.get<AuditLog>(`/api/audit-logs/${id}`);
    return data;
  }

  /**
   * 创建审计日志
   */
  async createAuditLog(auditLog: {
    action: string;
    description: string;
    level: 'info' | 'success' | 'warning' | 'error';
    metadata?: Record<string, any>;
  }): Promise<AuditLog> {
    const { data } = await apiClient.post<AuditLog>('/api/audit-logs', auditLog);
    return data;
  }

  /**
   * 导出审计日志
   */
  async exportAuditLogs(params: GetAuditLogsParams, format: 'csv' | 'excel' | 'json' = 'csv'): Promise<Blob> {
    const response = await apiClient.get('/api/audit-logs/export', {
      params: {
        ...params,
        format
      },
      responseType: 'blob'
    });
    return response.data;
  }

  /**
   * 清理审计日志
   */
  async cleanupAuditLogs(beforeDate: string): Promise<{ deletedCount: number }> {
    const { data } = await apiClient.delete<{ deletedCount: number }>('/api/audit-logs/cleanup', {
      data: { beforeDate }
    });
    return data;
  }

  /**
   * 获取系统统计信息
   */
  async getSystemStats(): Promise<{
    totalUsers: number;
    activeUsers: number;
    totalTenants: number;
    activeTenants: number;
    totalOrganizations: number;
    storageUsed: number;
    storageTotal: number;
    auditLogCount: number;
  }> {
    const { data } = await apiClient.get<{
      totalUsers: number;
      activeUsers: number;
      totalTenants: number;
      activeTenants: number;
      totalOrganizations: number;
      storageUsed: number;
      storageTotal: number;
      auditLogCount: number;
    }>(`${this.baseUrl}/stats`);
    return data;
  }

  /**
   * 测试邮件配置
   */
  async testEmailSettings(settings: {
    smtpHost: string;
    smtpPort: number;
    smtpUser: string;
    smtpPassword: string;
    testEmail: string;
  }): Promise<{ success: boolean; message: string }> {
    const { data } = await apiClient.post<{ success: boolean; message: string }>(`${this.baseUrl}/test-email`, settings);
    return data;
  }

  /**
   * 测试短信配置
   */
  async testSmsSettings(settings: {
    provider: string;
    apiKey: string;
    apiSecret: string;
    testPhone: string;
  }): Promise<{ success: boolean; message: string }> {
    const { data } = await apiClient.post<{ success: boolean; message: string }>(`${this.baseUrl}/test-sms`, settings);
    return data;
  }

  /**
   * 备份系统设置
   */
  async backupSettings(): Promise<Blob> {
    const response = await apiClient.get(`${this.baseUrl}/backup`, {
      responseType: 'blob'
    });
    return response.data;
  }

  /**
   * 恢复系统设置
   */
  async restoreSettings(file: File): Promise<{
    success: boolean;
    message: string;
    restoredSettings: string[];
  }> {
    const formData = new FormData();
    formData.append('file', file);
    
    const { data } = await apiClient.post<{
      success: boolean;
      message: string;
      restoredSettings: string[];
    }>(`${this.baseUrl}/restore`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    return data;
  }

  /**
   * 重置系统设置为默认值
   */
  async resetSettings(settingType: 'tenant' | 'organization' | 'system', targetId?: string): Promise<{
    success: boolean;
    message: string;
  }> {
    const { data } = await apiClient.post<{
      success: boolean;
      message: string;
    }>(`${this.baseUrl}/reset`, {
      settingType,
      targetId
    });
    return data;
  }

  /**
   * 获取设置变更历史
   */
  async getSettingsHistory(settingType: 'tenant' | 'organization' | 'system', targetId?: string): Promise<{
    id: string;
    settingType: string;
    targetId?: string;
    changes: Record<string, { from: any; to: any }>;
    changedBy: string;
    changedAt: string;
  }[]> {
    const { data } = await apiClient.get<{
      id: string;
      settingType: string;
      targetId?: string;
      changes: Record<string, { from: any; to: any }>;
      changedBy: string;
      changedAt: string;
    }[]>(`${this.baseUrl}/history`, {
      params: { settingType, targetId }
    });
    return data;
  }
}

export const settingsService = new SettingsService();